import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useAppDispatch, useAppSelector } from '@/store';
import { clearSuggestAction, getSuggetsAction } from '@/store/action/search';
import { sanitize } from 'dompurify';
import React, { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import useHistories from '@/hooks/useHistories';
import { useHistory } from 'react-router-dom';

export default function Search() {
  const dispatch = useAppDispatch();
  const history = useHistory();
  const { suggests } = useAppSelector((state) => state.search);
  const [keyword, setKeyword] = useState('');
  const { histories, handleAddHistories, handleClearHistories } = useHistories();

  const timerIdRef = useRef(-1);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.trim();
    setKeyword(value);

    clearTimeout(timerIdRef.current);
    timerIdRef.current = window.setTimeout(() => {
      if (!value) {
        dispatch(clearSuggestAction());
        return;
      }
      dispatch(getSuggetsAction(value));
    }, 1000);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSearch(keyword);
    }
  };

  const handleSearch = (key: string) => {
    handleAddHistories(key);
    history.push({
      pathname: '/search/result',
      search: `q=${key}`,
    });
  };

  useEffect(() => {
    return () => {
      clearTimeout(timerIdRef.current);
      dispatch(clearSuggestAction());
    };
  }, [dispatch]);

  return (
    <div className={styles.root}>
      <NavBar
        right={
          <span className="search-text" onClick={() => handleSearch(keyword)}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            <input
              type="text"
              placeholder="请输入关键字搜索"
              value={keyword}
              onChange={handleChange}
              onKeyDown={handleKeyDown}
            />

            <Icon type="iconbtn_tag_close" className="icon-close" />
          </div>
        </div>
      </NavBar>

      {!keyword && (
        <div className="history" style={{ display: 'block' }}>
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={handleClearHistories}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {histories.map((item, index) => {
              return (
                <span
                  onClick={() => handleSearch(item)}
                  key={index}
                  className="history-item"
                >
                  {item}
                  <span className="divider"></span>
                </span>
              );
            })}
          </div>
        </div>
      )}

      <div className="search-result">
        {suggests.map((item, index) => {
          return (
            <div key={index} className="result-item" onClick={() => handleSearch(item)}>
              <Icon className="icon-search" type="iconbtn_search" />
              <div
                className="result-value"
                dangerouslySetInnerHTML={{
                  __html: sanitize(highlight(keyword, item)),
                }}
              />
            </div>
          );
        })}
      </div>
    </div>
  );
}

function highlight(keyword: string, target: string) {
  const reg = new RegExp(`(${keyword})`, 'gi');
  return target.replace(reg, '<span onclick="alert(123)">$1</span>');
}
